
=begin 
Copyright (c) <2009> <Sheheryar Sewani, Sheysrebellion@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
=end


require 'rubygems'
require 'httparty'
require 'mash'
require 'digest/md5'



module MoneyTracking
  
  class MoneyTrackin
    def initialize(connection)
      @conn = connection
    end

    def get_accounts
      @conn.list_projects
    end

    def new_account(account_name, currency="USD")
      @conn.new_project(account_name, currency)
    end

    def get_balance(account_id="")
      @conn.get_balance(account_id)
    end

    def write_accounts
      @conn.list_write_projects
    end

    def get_tags(project_id="")
      @conn.get_tags(project_id)
    end

    def currencies
      @conn.list_currencies
    end

    def transactions(project_id="",start_date='1901-01-01', end_date=Time.now.strftime("%Y-%m-%d"), tag="")
      if tag != ""
        @conn.list_transactions_using_tags(project_id, start_date, end_date, tag)
      else
        @conn.list_transactions(project_id, start_date, end_date)
      end
    end

    #does not support periodic transactoins
    def add_transaction(project_id, description, amount, transaction_date, tag_list)
     
      if transaction_date == ""
        transaction_date = Time.now.strftime("%Y-%m-%d")
      end

      tags = tag_list.join(" ")

      @conn.insert_transaction(project_id, description, amount, transaction_date, tags)
    end

    
    def delete_account(account_id="")
      @conn.delete_project(account_id)
    end

    def delete_transaction(transaction_id="")
      @conn.delete_transaction(transaction_id)
    end

  end


  class HttpAuth
    include HTTParty
    
    default_params :output => 'xml'
    format :xml
    
    def initialize(user, pass)
      @object_extracter = XmlExtractor.new()
      hashed_password = Digest::MD5.hexdigest(pass)
      self.class.basic_auth user, hashed_password
      self.class.base_uri 'https://www.moneytrackin.com/api/rest/'
    end
    
    def list_projects
      response = self.class.get(self.class.base_uri + '/listProjects/')
      accounts = @object_extracter.extract_objects(response, 'project')
      return accounts
    end

    def list_write_projects
      response = self.class.get(self.class.base_uri + '/listWriteProjects/')
      accounts = @object_extracter.extract_objects(response, 'project')
      return accounts
    end

    def get_balance(project_id="")
      response = self.class.get(self.class.base_uri + '/getBalance/',
        :query => {:project => project_id})
      balance = @object_extracter.extract_single_value(response, 'balance')
      return balance
    end

    def list_transactions(project_id, start_date, end_date )
      response = self.class.get(self.class.base_uri + '/listTransactions/',
        :query => {:project => project_id, :startDate => start_date, :endDate => end_date})
      transactions = @object_extracter.extract_objects(response, 'transaction')
      return transactions
    end

    def list_transactions_using_tags(project_id, start_date, end_date, tag )
      response = self.class.get(self.class.base_uri + '/listTagTransactions/',
        :query => { :project => project_id, :startDate => start_date, :endDate => end_date,
                    :tag => tag})
      transactions = @object_extracter.extract_objects(response, 'transaction')
      return transactions
    end
    
    def get_tags(project_id="")
      response = self.class.get(self.class.base_uri + '/getTags/',
         :query => {:project => project_id})
      tags = @object_extracter.extract_objects(response, 'tag')
      return tags
    end

    def list_currencies
      response = self.class.get(self.class.base_uri + '/listCurrencies/')
      currencies = @object_extracter.extract_objects(response, 'currency')
      return currencies
    end

    def delete_project(project_id="")
      self.class.get(self.class.base_uri + '/deleteProject/', :query => {:projectID => project_id})
    end

    def delete_transaction(transaction_id="")
      self.class.get(self.class.base_uri + '/deleteProject/', :query => {:transactionID  => transaction_id})
    end

    def new_project(project_name, currency)
      self.class.get(self.class.base_uri + '/newProject/', 
        :query => {:projectName  => project_name, :currency => currency})
    end

    def insert_transaction(project_id, description, amount, transaction_date, tags)
      self.class.get(self.class.base_uri + '/insertTransaction/',
        :query  => {:project  => project_id, :description  => description,
        :amount => amount, :date => transaction_date, :tags => tags})
    end

  end #end HttpAuth class
  
  class XmlExtractor
    def extract_objects(xml_response,key)
      objects = Array.new()
      
      if xml_response['result'][key] == nil
        return objects
      end

      if xml_response['result'][key].class == Hash
        objects << extract_object(xml_response, key)
      else
        xml_response['result'][key].each { |o| objects << Mash.new(o) }
      end
      
      return objects
    end

    def extract_object(xml_response, key)
      return Mash.new(xml_response['result'][key])
    end

    def extract_single_value(xml_response, key)
      return xml_response['result'][key]
    end
    
  end #end xml class
  
  
  
  
end #end module